package com.yima.baseproj.security.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yima.baseproj.security.SecurityUtil;
import com.yima.baseproj.security.utils.jwt.JwtUtil;
import com.yima.baseproj.security.model.UserLoginAuthModel;
import com.yima.baseproj.security.exception.LoginAuthenticationException;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT请求令牌过滤器
 * @Author 一码
 * @createDate 2023/4/1 09:00
 * @contact 1424529270@qq.com
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter{

    @SneakyThrows
    @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {

        //获取token
        String token = request.getHeader(SecurityUtil.HEADER_TOKEN);
        //校验token是否为空
        if(StrUtil.isBlank(token)){
            filterChain.doFilter(request,response);
            return;
        }
        //校验token前缀
        if(token.startsWith(SecurityUtil.BEARER)){
            token = token.substring(SecurityUtil.BEARER.length());
        }else{
            filterChain.doFilter(request,response);
            return;
        }
        //校验token是否为空
        if(StrUtil.isBlank(token)){
            filterChain.doFilter(request,response);
            return;
        }

        //解析token
        Boolean checkToken = JwtUtil.checkToken(token);
        if(!checkToken){
            throw LoginAuthenticationException.JWT_WUXIAO;
        }
        Claims claims = JwtUtil.getBodyByToken(token);
        String userId = claims.getSubject();
        String client = claims.getAudience();
        //从redis获取用户信息并做为空判断
        JSONObject userLoginJsonObject = SecurityUtil.getTokenToRedis(client,userId);
        if(ObjectUtil.isNull(userLoginJsonObject)){
            throw LoginAuthenticationException.JWT_EXPIRED;
        }
        UserLoginAuthModel userLoginAuthModel = JSON.parseObject(JSON.toJSONString(userLoginJsonObject), UserLoginAuthModel.class);
        //获取权限
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userLoginAuthModel,null, userLoginAuthModel.getAuthorities());

        //存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
